﻿/*
 *GreyBox was written by Strategic Data Systems and licenced under the open source MS-PL. 
 */
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;
using System.Net;

namespace StrategicDataSystems.Cloud.Monitoring.HostedServices.ResponseToEntityMappers
{
    public class OperationStatusResponseMapper
    {
        public HostedServiceOperationStatus MapToEntity(XDocument responseXml)
        {
            XNamespace azureNamespace = XNamespace.Get("http://schemas.microsoft.com/windowsazure");

            HostedServiceOperationStatus status = (from operationElement in responseXml.Descendants(azureNamespace + "Operation")
                                     select new HostedServiceOperationStatus(
                                         operationId: operationElement.Element(azureNamespace + "ID").Value,
                                         status: operationElement.Element(azureNamespace + "Status").Value)
                                     ).First();

            if (status.Status == OperationStatus.Failed)
            {
                var errorInfo = (from operationElement in responseXml.Descendants(azureNamespace + "Error")
                                 select new {
                                     Code = operationElement.Element(azureNamespace + "Code").Value,
                                     Message = operationElement.Element(azureNamespace + "Message").Value}
                                     ).First();

                throw new WebException(string.Format(
                                           "Azure request ID:{0} failed with error code: {1}. Message: {2}", 
                                           status.OperationId, 
                                           errorInfo.Code, 
                                           errorInfo.Message));
            }

            return status;
        }
    }
}
